<?php

namespace Frieza\Modules\Decoration\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Category;
use Doraemon\model\Decoration\Adv as mAdv;
use Doraemon\model\Decoration\Category as mCategory;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\model\Decoration\Tag as mTag;
use Doraemon\service\Decoration\Main as sMain;

class IndexController extends Controller
{

    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }


    public function index(Request $request,Content $content, $step)
    {
        $request = $request->all();
        $tab = new Tab();

        $tab->addLink('分类', '/admin/decoration/index/1', $step == 1);
        $tab->addLink('主题', '/admin/decoration/index/2', $step == 2);
        //$tab->addLink('热搜词', '/admin/decoration/index/3', $step == 3);
        //$tab->addLink('资源位', '/admin/decoration/index/4', $step == 4);


        return $content
            ->header('装修')
            ->breadcrumb(
                ['text' => '分类', 'url' => '/admin/decoration/index/'.$step]
            )
            ->body($tab)->row(self::_form($request, $step));
	}

    private function _form($request, $step)
    {
        $request = self::_filterWhere($request);

        $subject = mSubject::getAllByWhere(['status'=>mSubject::STATUS_OPEN],['id','name']);
        $subjects = [];
        if (!empty($subject)) {
            foreach ($subject as &$_v) {
                $subjects[$_v['id']] = $_v['name'];
            }
        }

        $category = mCategory::getAllByWhere(['parent_id'=>0,'status'=>mCategory::STATUS_OPEN],['id','title']);
        $categorys = [];
        if (!empty($category)) {
            foreach ($category as &$_v) {
                $categorys[$_v['id']] = $_v['title'];
            }
        }

        switch ($step){
            case 1:
                return self::categorys($request, $categorys).self::categorysList($request);
                break;
            case 2:
                return self::subjects($request).self::subjectsList($request);
                break;
//            case 3:
//                return self::tags($request, $subjects).self::tagsList($request, $subjects);
//                break;
//            case 4:
//                return self::advs($request, $subjects).self::advsList($request);
//                break;
        }
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }

        $data = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
                if($_k == 'date_time') {
                    if ($where[$_k]['start'] <> '') {
                        $where['start_time[>=]'] = $where[$_k]['start'];
                        unset($where[$_k]['start']);
                    }
                    if ($where[$_k]['end'] <> '') {
                        $where['end_time[<]'] = $where[$_k]['end'];
                        $where[$_k]['end'];
                    }
                    unset($where[$_k]);
                }
            }
        }

        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function categorys($request, $categorys){

        if(!empty($request['AND']['id'])){
            $data = mCategory::getOneByWhere(['id'=>$request['AND']['id']]);
            if(isset($data['parent_id']) && $data['parent_id']<1) {
                $categorys = [];
            }
        }else{
            $data = [];
        }

        $form = new Form($data);

        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        if (!empty($categorys)) {
            $form->select('parent_id', '上级分类')
                ->options($categorys)
                ->setWidth(4, 2)
               ;
        }

        $form->text('title', '标题')->setWidth(4, 2)->required('不能为空');
        $form->text('sort', '权重')->setWidth(4, 2)->required('不能为空');
        $form->radio('is_show', '是否显示')
            ->options([0=>'否', 1=>'是'])
            ->setWidth(4, 2);
        $form->radio('is_cover', '是否需要封面')
            ->options([0=>'否', 1=>'是'])
            ->options([0=>'否', 1=>'是'])
            ->setWidth(4, 2);

        $form->action('/admin/decoration/category/edit');

        return $form->render();
    }

    public function categorysList($request = []){
        $category = sMain::getCategory($request);
        $gridModel = new pGridDataModel($category['list'], $category['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            //$grid->disableFilter();
            //$grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('title', '标题')->placeholder('请输入标题');
                });
            });

            $grid->column('id', 'id');
            $grid->column('parent_id', '上级分类')->display(function(){
                if($this->parent_id>0){
                    return $this->parent_name;
                }else{
                    return '顶级分类';
                }
            });
            $grid->column('title', '标题');

            $status = [
                'on' => [
                    'value' => mCategory::SHOW_OPEN,
                    'text' => '是'
                ],
                'off' => [
                    'value' => mCategory::SHOW_CLOSE,
                    'text' => '否'
                ],
            ];
            $grid->column('is_show', '是否显示')->switchToggle($status);
            $grid->column('is_cover', '是否需要封面')->switchToggle($status);
            $grid->column('sort', '权重');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('add_time', '添加时间');

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                $actions->append("<a href=\"/admin/decoration/index/1?id=".$actions->row->id."\" class=\"btn btn-primary\">编辑</a>");
                $actions->append("<a href=\"/admin/decoration/category/del/".$actions->row->id."\" class=\"btn btn-primary\" onclick=\"return confirm('确认删除！！！'); \">删除</a>");
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    public function subjects($request){
        $wiki_category = sMain::getWikiCategory();
        $category = mCategory::getAllByWhere(['parent_id[>]'=>0,'status'=>mCategory::STATUS_OPEN],['id','title']);
        $categorys = [];
        if (!empty($category)) {
            foreach ($category as &$_v) {
                $categorys[$_v['id']] = $_v['title'];
            }
        }

        if(!empty($request['AND']['id'])){
            $data = mSubject::getOneByWhere(['id'=>$request['AND']['id']]);
        }else{
            $data = [];
        }

        $form = new Form($data);

        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        $form->text('name', '主题名称')->setWidth(4, 2)->required('不能为空');
        $form->color('color', '主题背景色')->setWidth(4, 2)->required('不能为空');
        $form->text('rela_tag', '关联tag');
        $form->multipleSelect('rela_wiki', '关联wiki分类')->options(Category::getCategorysByDeep([1,2,3]));
//        $form->checkbox('rela_wiki2', '关联wiki分类') ->options($wiki_category);
        $form->text('search_tag', '搜索描述')->setWidth(4, 2);

        $form->action('/admin/decoration/subject/edit');

        return $form->render();
    }

    public function subjectsList($request = []){
        $subject = sMain::getSubject($request);
        $gridModel = new pGridDataModel($subject['list'], $subject['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            //$grid->disableFilter();
            //$grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '主题名称')->placeholder('请输入主题名称');
                });
            });
            $grid->tools(function (Grid\Tools $tool) {
                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '全部资源位', '', '/admin/decoration/adv/0'));
            });
//            $grid->tools(function (Grid\Tools $tool) {
//                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '添加热搜词', '', '/admin/decoration/tag/0'));
//            });

            $grid->column('id', 'id');
            $grid->column('name', '主题名称');
            $grid->column('color', '背景颜色')->display(function(){
                return '<p style="background-color: '.$this->color.';color:'.$this->color.';width: 50px; display: block">颜色</p>';
            });
            $grid->column('rela_tag', '关联tag');
            $grid->column('rela_wiki', '关联wiki分类');
            $grid->column('search_tag', '搜索描述');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                $actions->append("<a href=\"/admin/decoration/index/2?id=".$actions->row->id."\" class=\"btn btn-primary\">编辑</a>");
                $actions->append("<a href=\"/admin/decoration/subject/del/".$actions->row->id."\" class=\"btn btn-primary\" onclick=\"return confirm('确认删除！！！'); \">删除</a>");
                $actions->append("<a href=\"/admin/decoration/tag/".$actions->row->id."\" class=\"btn btn-primary\" >热搜词</a>");
                $actions->append("<a href=\"/admin/decoration/adv/".$actions->row->id."\" class=\"btn btn-primary\" >资源位</a>");
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    public function tags($request, $subjects =[]){

        if(!empty($request['AND']['id'])){
            $data = mTag::getOneByWhere(['id'=>$request['AND']['id']]);
        }else{
            $data = [];
        }

        $form = new Form($data);

        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        $form->select('sid', '隶属主题')
            ->options($subjects)
            ->setWidth(4, 2)
            ->required('不能为空');
        $form->text('name', '名称')->setWidth(4, 2)->required('不能为空');
        $form->text('sort', '权重')->setWidth(4, 2)->required('不能为空');
        $form->text('link', '跳转链接')->setWidth(4, 2)->default('hhz://search-tag:')->required('不能为空');

        $form->action('/admin/decoration/tag/edit');

        return $form->render();
    }

    public function tagsList($request = [], $subjects =[]){
        $tag = sMain::gettag($request);
        $gridModel = new pGridDataModel($tag['list'], $tag['total'], [
            'perPage' => self::PAGE_SIZE
        ]);


        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($subjects) {
            //$grid->disableFilter();
            //$grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter)use($subjects) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter)use($subjects) {
                    $filter->equal('sid', '主题')->select($subjects);
                });
                $filter->column(1 / 2, function ($filter){
                    $filter->equal('name', '名称')->placeholder('请输入名称');
                });
            });

            $grid->column('id', 'id');
            $grid->column('sid_name', '主题');
            $grid->column('name', '名称');
            $grid->column('sort', '权重');
            $grid->column('link', '链接');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                $actions->append("<a href=\"/admin/decoration/index/3?id=".$actions->row->id."\" class=\"btn btn-primary\">编辑</a>");
                $actions->append("<a href=\"/admin/decoration/tag/del/".$actions->row->id."\" class=\"btn btn-primary\" onclick=\"return confirm('确认删除！！！'); \">删除</a>");
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    public function advs($request,$subjects){
        $show_type = mAdv::SHOW_TYPE;
        $category = mCategory::getAllByWhere(['status'=>mCategory::STATUS_OPEN],['id','title','parent_id']);
        $categorys = [];
        if (!empty($category)) {
            foreach ($category as &$_v) {
                if($_v['parent_id'] == 0){
                    $categorys['parent'][$_v['id']] = $_v['title'];
                }else{
                    $categorys['son'][$_v['id']] = $_v['title'];
                }
            }
        }

        if(!empty($request['AND']['id'])){
            $data = mAdv::getOneByWhere(['id'=>$request['AND']['id']]);
            $id = $request['AND']['id'];
        }else{
            $data = [];
            $id = 0;
        }
        $dataJsons = $data;
        unset($dataJsons['link']);
        $dataJson = json_encode($dataJsons, true);

        $script =
<<<SCRIPT
      var data_json = $.parseJSON('{$dataJson}');
      var cur_id = {$id};
      var showtype = $('.show_type');
      var category_1 = $('input.category_1');
      var category_2 = $('input.category_2');
      var side = category_2.parents('.form-group').next('.form-group');
      var name = $('#name').parents('.form-group');
      
      category_1.parents('.form-group').hide();
      category_2.parents('.form-group').hide();
      side.hide();
      name.hide();

     
      if(cur_id > 0){
          side.show();
          name.show();
          var cid = data_json.rela_id.split(',');
          if(data_json.show_type == 4006){  
              $.each(category_2, function(ck, cv){ 
                    var cur = $(this); 
                    if($.inArray(cur.val(), cid) >= 0){
                        cur.iCheck('check');
                    }
              });
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').show();
              name.hide();
          }else if(data_json.show_type == 4007){
              $.each(category_1, function(ck, cv){ 
                    var cur = $(this); 
                    if($.inArray(cur.val(), cid) >= 0){
                        cur.iCheck('check');
                    }
              });
              category_1.parents('.form-group').show();
              category_2.parents('.form-group').hide();
              side.hide();
          }else if(data_json.show_type == 4008){
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').hide();
          }else if(data_json.show_type == 4009){
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').hide();
          }  
          
      }else{
          $('input.link_type').first().iCheck('check');
          $('input.link').val($('input.link_type').first().val());
      }
      
      
       $('input.link_type').on('ifChecked ifUnchecked', function(event) {
           if (event.type == 'ifChecked'){
            $('input.link').val($(this).val());
           }
        });
   
        showtype.on('select2:select', function (e) {
              side.show();
              name.show();
              var data = e.params.data.id;
              if(data == 4006){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').show();
                  name.hide();
              }else if(data == 4007){
                  category_1.parents('.form-group').show();
                  category_2.parents('.form-group').hide();
                  side.hide();
              }else if(data == 4008){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').hide();
              }else if(data == 4009){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').hide();
              }
        });
       
      

SCRIPT;


        Admin::script($script);
        //Admin::script('imgUpload.one();');
        $form = new Form($data);

        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        $form->select('show_type', '位置')
            ->options($show_type)
            ->setWidth(4, 2)
            ->required('不能为空');
        ;

        $form->checkbox('category_1','关联一级分类')->options(isset($categorys['parent'])?$categorys['parent']:[]);
        $form->checkbox('category_2','关联二级分类')->options(isset($categorys['son'])?$categorys['son']:[]);
        $form->select('sid', '关联主题')->options($subjects)->setWidth(4, 2);

        $form->text('name', '名称')->setWidth(4, 2);
        $form->text('sort', '权重')->setWidth(4, 2)->required('不能为空');
        $form->radio('link_type', '链接选择')->options(
            [
                'hhz://search-tag:'=>'搜索结果',
                'hhz://blank:'=>'文章',
                'hhz://guide:'=>'指南',
                'hhz://decorate_tag:'=>'装修主题',
                'hhz://specialItem:' => '专题',
                'hhz://topic_detail:{"topic_id":"","search_type":"2","sort_type":"1"}' => '话题',
                'hhz://ideabook:' => '灵感集',
                'hhz://article:' => '整屋',
                'hhz://note:{"note_id":"","pin_id""}' => 'note',
            ]
        );
        $form->text('link', '链接')->required('不能为空');

        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
//        $form->image('pic_id_url', '封面')->attribute('img-upload', 'pic_id');
//        $form->hidden('pic_id');
        $form->imgUpload('pic_id', '封面');

        if(isset($request['AND'])){
            foreach($request['AND'] as $_k=>&$_v){
                if(!empty($_v)){
                    $_k = str_replace('[>=]','', $_k);
                    $_k = str_replace('[<]','', $_k);
                    $url_request[] =  $_k.'='.$_v;
                }
            }
            $url_request = implode('&', $url_request);
            $form->action('/admin/decoration/adv/edit?'.$url_request);
        }else{
            $form->action('/admin/decoration/adv/edit');
        }

        return $form->render();
    }

    public function advsList($request){
        $get = $_SERVER["QUERY_STRING"]?'?'.$_SERVER["QUERY_STRING"]:'';
        //按名称搜索时
        if(!empty($request['AND']['name'])){
            $sid = mSubject::getOneByWhere(['name'=>$request['AND']['name']],'id');
            if($sid){
                $request['OR'] = [
                    'sid'=> $sid,
                    'name'=> $request['AND']['name'],
                ];
                unset($request['AND']['name']);
                if(empty($request['AND'])){
                    unset($request['AND']);
                }
            }
        }

        $adv = sMain::getAdv($request);
        $gridModel = new pGridDataModel($adv['list'], $adv['total'], [
            'perPage' => self::PAGE_SIZE,
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($get) {
            //$grid->disableFilter();
            //$grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
//                    $filter->equal('start_time', '开始时间')->dateTime();
//                    $filter->equal('end_time', '结束时间')->dateTime();
                    $filter->between('date_time', '广告时间')->datetime()->condition($_GET);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('show_type', '广告位置')->select(mAdv::SHOW_TYPE);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '名称')->placeholder('请输入名称');
                });
            });

            $grid->column('id', 'id');
            $grid->column('rela_id', '关联分类');
            $grid->column('sid', '关联主题');
            $grid->column('show_type', '广告位置')->display(function(){
                return mAdv::SHOW_TYPE[$this->show_type];
            });
            $grid->column('name', '名称');
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('sort', '权重');
            $grid->column('link', '链接');
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '更新时间');
            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions)use($get){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                if($actions->row->status < 2) {
                    $actions->append("<a href=\"/admin/decoration/index/4?id=" . $actions->row->id . "\" class=\"btn btn-primary\">编辑</a>");
                    $actions->append("<a href=\"/admin/decoration/adv/del/" . $actions->row->id . $get . "\" class=\"btn btn-primary\" onclick=\"return confirm('确认删除！！！'); \">删除</a>");
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }


}